using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCW.Friends;
using UnityEngine;

public class LeaderBoardServer : MonoBehaviour
{
	public const string KEY_TIME_LAST_LOAD_LEADERS = "keyTimeLastLoadLeaders";

	public const string KEY_TIME_LAST_LOAD_LEADERS_COMMON = "keyTimeLastLoadLeadersCommon";

	public const string KEY_TIME_LAST_LOAD_MY = "keyTimeLastLoadMy";

	public const string KEY_TIME_LAST_LOAD_MY_COMMON = "keyTimeLastLoadMyCommon";

	public const string KEY_LAST_LEAGUE = "keyLastLeague";

	public const string KEY_LAST_LEAGUE_COMMON = "keyLastLeagueCommon";

	public const string KEY_LAST_LEAGUE_MY = "keyLastLeagueMy";

	public const string KEY_LAST_LEAGUE_MY_COMMON = "keyLastLeagueMyCommon";

	public const string LEY_LEADERS_BY_TYPE_GAME = "keyLeaders";

	public const string LEY_LEADERS_COMMON = "keyLeadersCommon";

	public const string KEY_PLAYER_INFO = "keyPlayerInfo";

	public const string KEY_PLAYER_INFO_COMMON = "keyPlayerCommonInfo";

	public static LeaderBoardServer instance;

	private bool _isTest;

	private void Awake()
	{
		instance = this;
	}

	private void OnDestroy()
	{
		instance = null;
	}

	public static int TypeForLeaderboard(TypeGame typeGame)
	{
		switch (typeGame)
		{
		case TypeGame.TDM:
			return 1;
		case TypeGame.normal:
			return 2;
		case TypeGame.race:
			return 3;
		case TypeGame.tanks:
			return 4;
		case TypeGame.Zombe:
			return 5;
		case TypeGame.CopsAndRobbers:
			return 6;
		case TypeGame.Offline:
			return 7;
		case TypeGame.SkyBlock:
			return 8;
		case TypeGame.RocketLeague:
			return 9;
		case TypeGame.Pixelmon:
			return 11;
		case TypeGame.WalkingRobots:
			return 12;
		case TypeGame.TitanfallV2:
			return 13;
		default:
			return 0;
		}
	}

	public void SendStars(int stars, TypeGame game)
	{
		StartCoroutine(IESendStars(stars, game));
	}

	private IEnumerator IESendStars(int stars, TypeGame game)
	{
		BCWDebug.Log("SendStars");
		while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
		{
			yield return new WaitForSeconds(1f);
		}
		WWWForm form = new WWWForm();
		form.AddField("action", "update_player_stars");
		form.AddField("app_version", BCWServer._version);
		form.AddField("id", BCWServer.idPlayer);
		form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague));
		form.AddField("stars", stars);
		form.AddField("game", TypeForLeaderboard(game));
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			BCWServer.HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		yield return www;
		string result = BCWServer.Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("Error download:  " + www.error);
			yield break;
		}
		if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("SendStars failed ");
			yield break;
		}
		if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("SendStars result is empty");
			yield break;
		}
		BCWDebug.Log("SendStars result  " + result);
		LeaderBoardStarsStorage.GetInstance().AddStars(game, stars);
	}

	public void GetPlayerInfo()
	{
		StartCoroutine(IEGetPlayerInfo());
	}

	private IEnumerator IEGetPlayerInfo()
	{
		if (!_isTest)
		{
			for (int i = 1; i <= 3; i++)
			{
				if (!JSONManager.Instance.ServerTimeLoad())
				{
					if (i == 3)
					{
						yield break;
					}
					yield return new WaitForSeconds(0.5f);
				}
			}
		}
		BCWDebug.Log("GetPlayerInfo");
		int currentLeague = BCWStorage.Get<int>(CupsManager.keyCurrentLeague);
		if (PlayerPrefs.GetInt("keyLastLeagueMy") != currentLeague || PlayerPrefs.GetInt("keyTimeLastLoadMy") <= JSONManager.Instance.GetServerTime() || _isTest)
		{
			while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
			{
				yield return new WaitForSeconds(1f);
			}
			WWWForm form = new WWWForm();
			form.AddField("action", "get_my_stars");
			form.AddField("app_version", BCWServer._version);
			form.AddField("id", BCWServer.idPlayer);
			form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague));
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				BCWServer.HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			yield return www;
			string result = BCWServer.Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.Log("Error download get_my_stars:  " + www.error);
				yield break;
			}
			if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				BCWDebug.Log("GetPlayerInfo failed ");
				yield break;
			}
			if (string.IsNullOrEmpty(result))
			{
				BCWDebug.Log("GetPlayerInfo result is empty");
				yield break;
			}
			BCWDebug.Log("GetPlayerInfo result  " + result);
			PlayerPrefs.SetString("keyPlayerInfo", result);
			LeaderBoardStarsStorage.GetInstance().Reset();
			PlayerPrefs.SetInt("keyTimeLastLoadMy", JSONManager.Instance.GetServerTime() + 7200);
			PlayerPrefs.SetInt("keyLastLeagueMy", currentLeague);
		}
	}

	public void LoadLeaderBoardTypeGameInfo()
	{
		StartCoroutine(IELoadLeaderBoardTypeGameInfo());
	}

	private IEnumerator IELoadLeaderBoardTypeGameInfo()
	{
		if (!_isTest)
		{
			for (int i = 1; i <= 3; i++)
			{
				if (!JSONManager.Instance.ServerTimeLoad())
				{
					if (i == 3)
					{
						yield break;
					}
					yield return new WaitForSeconds(0.5f);
				}
			}
		}
		int currentLeague = BCWStorage.Get<int>(CupsManager.keyCurrentLeague);
		if (PlayerPrefs.GetInt("keyLastLeague") == currentLeague && PlayerPrefs.GetInt("keyTimeLastLoadLeaders") > JSONManager.Instance.GetServerTime() && !_isTest)
		{
			yield break;
		}
		while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
		{
			yield return new WaitForSeconds(1f);
		}
		WWWForm form = new WWWForm();
		form.AddField("action", "get_leaderboards_stars");
		form.AddField("app_version", BCWServer._version);
		form.AddField("id", BCWServer.idPlayer);
		form.AddField("rank", currentLeague);
		List<string> idsPlayers = new List<string>();
		idsPlayers.Add(BCWServer.idPlayer);
		idsPlayers.AddRange(FriendsController.instance.FriendsIds.ToList());
		form.AddField("friends", string.Join(",", idsPlayers.ToArray()));
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			BCWServer.HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		yield return www;
		string result = BCWServer.Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			BCWDebug.Log("Error download get_leaderboards_stars:  " + www.error);
			yield break;
		}
		if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			BCWDebug.Log("LoadInfo failed ");
			yield break;
		}
		if (string.IsNullOrEmpty(result))
		{
			BCWDebug.Log("LoadInfo result is empty");
			yield break;
		}
		BCWDebug.Log("LoadInfo result  " + result);
		Dictionary<string, string> tmpDictionaryGroup = CustomParse(result);
		foreach (KeyValuePair<string, string> pairGroup in tmpDictionaryGroup)
		{
			Dictionary<string, string> tmpDictionaryTypeGame = CustomParse(pairGroup.Value);
			foreach (KeyValuePair<string, string> pairTypeGame in tmpDictionaryTypeGame)
			{
				PlayerPrefs.SetString("keyLeaders" + pairGroup.Key + pairTypeGame.Key, pairTypeGame.Value);
			}
		}
		PlayerPrefs.SetInt("keyTimeLastLoadLeaders", JSONManager.Instance.GetServerTime() + 7200);
		PlayerPrefs.SetInt("keyLastLeague", currentLeague);
	}

	public void LoadLeaderBoardCommonInfo()
	{
		StartCoroutine(IELoadLeaderBoardCommonInfo());
	}

	private IEnumerator IELoadLeaderBoardCommonInfo()
	{
		if (!_isTest)
		{
			for (int i = 1; i <= 3; i++)
			{
				if (!JSONManager.Instance.ServerTimeLoad())
				{
					if (i == 3)
					{
						yield break;
					}
					yield return new WaitForSeconds(0.5f);
				}
			}
		}
		int currentLeague = BCWStorage.Get<int>(CupsManager.keyCurrentLeague);
		if (PlayerPrefs.GetInt("keyLastLeagueCommon") != currentLeague || PlayerPrefs.GetInt("keyTimeLastLoadLeadersCommon") <= JSONManager.Instance.GetServerTime() || _isTest)
		{
			while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
			{
				yield return new WaitForSeconds(1f);
			}
			WWWForm form = new WWWForm();
			form.AddField("action", "get_top_leaderboards_stars");
			form.AddField("app_version", BCWServer._version);
			form.AddField("id", BCWServer.idPlayer);
			form.AddField("rank", currentLeague);
			List<string> idsPlayers = new List<string>();
			idsPlayers.Add(BCWServer.idPlayer);
			idsPlayers.AddRange(FriendsController.instance.FriendsIds.ToList());
			form.AddField("friends", string.Join(",", idsPlayers.ToArray()));
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				BCWServer.HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			yield return www;
			string result = BCWServer.Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.Log("Error download get_top_leaderboards_stars:  " + www.error);
				yield break;
			}
			if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				BCWDebug.Log("LoadInfoCommon failed ");
				yield break;
			}
			if (string.IsNullOrEmpty(result))
			{
				BCWDebug.Log("LoadInfoCommon result is empty");
				yield break;
			}
			BCWDebug.Log("LoadInfoCommon result  " + result);
			PlayerPrefs.SetString("keyLeadersCommon", result);
			PlayerPrefs.SetInt("keyTimeLastLoadLeadersCommon", JSONManager.Instance.GetServerTime() + 7200);
			PlayerPrefs.SetInt("keyLastLeagueCommon", currentLeague);
		}
	}

	public void GetPlayerCommonInfo()
	{
		StartCoroutine(IEGetPlayerCommonInfo());
	}

	private IEnumerator IEGetPlayerCommonInfo()
	{
		if (!_isTest)
		{
			for (int i = 1; i <= 3; i++)
			{
				if (!JSONManager.Instance.ServerTimeLoad())
				{
					if (i == 3)
					{
						yield break;
					}
					yield return new WaitForSeconds(0.5f);
				}
			}
		}
		BCWDebug.Log("GetPlayerCommonInfo");
		int currentLeague = BCWStorage.Get<int>(CupsManager.keyCurrentLeague);
		if (PlayerPrefs.GetInt("keyLastLeagueMyCommon") != currentLeague || PlayerPrefs.GetInt("keyTimeLastLoadMyCommon") <= JSONManager.Instance.GetServerTime() || _isTest)
		{
			while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
			{
				yield return new WaitForSeconds(1f);
			}
			WWWForm form = new WWWForm();
			form.AddField("action", "get_my_rank");
			form.AddField("app_version", BCWServer._version);
			form.AddField("id", BCWServer.idPlayer);
			form.AddField("rank", BCWStorage.Get<int>(CupsManager.keyCurrentLeague));
			List<string> idsPlayers = new List<string>();
			idsPlayers.Add(BCWServer.idPlayer);
			idsPlayers.AddRange(FriendsController.instance.FriendsIds.ToList());
			form.AddField("friends", string.Join(",", idsPlayers.ToArray()));
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				BCWServer.HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			yield return www;
			string result = BCWServer.Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.Log("Error download get_my_rank:  " + www.error);
				yield break;
			}
			if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				BCWDebug.Log("GetPlayerCommonInfo failed ");
				yield break;
			}
			if (string.IsNullOrEmpty(result))
			{
				BCWDebug.Log("GetPlayerCommonInfo result is empty");
				yield break;
			}
			BCWDebug.Log("GetPlayerCommonInfo result  " + result);
			PlayerPrefs.SetString("keyPlayerCommonInfo", result);
			LeaderBoardStarsStorage.GetInstance().Reset();
			PlayerPrefs.SetInt("keyTimeLastLoadMyCommon", JSONManager.Instance.GetServerTime() + 7200);
			PlayerPrefs.SetInt("keyLastLeagueMyCommon", currentLeague);
		}
	}

	private Dictionary<string, string> CustomParse(string jsonString)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (string.IsNullOrEmpty(jsonString))
		{
			return dictionary;
		}
		StringBuilder stringBuilder = new StringBuilder();
		StringBuilder stringBuilder2 = new StringBuilder();
		int num = 0;
		bool flag = false;
		char c = ' ';
		jsonString = jsonString.Trim();
		string text = jsonString;
		for (int i = 0; i < text.Length; i++)
		{
			char c2 = text[i];
			if (num == 1)
			{
				if (c2.Equals('"'))
				{
					flag = !flag;
				}
				else if (flag)
				{
					stringBuilder.Append(c2);
				}
			}
			else if (num > 1)
			{
				stringBuilder2.Append(c2);
				if (c2.Equals('"'))
				{
					flag = !flag;
				}
			}
			if (!flag && (c2.Equals('{') || c2.Equals('[')))
			{
				if (num == 1)
				{
					c = c2;
				}
				num++;
			}
			if (!flag && (c2.Equals('}') || c2.Equals(']')))
			{
				num--;
				if (num == 1)
				{
					dictionary.Add(stringBuilder.ToString(), c + stringBuilder2.ToString());
					stringBuilder = new StringBuilder();
					stringBuilder2 = new StringBuilder();
				}
			}
		}
		return dictionary;
	}
}
